package com.funtonow.jqdk.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.bean.DkNumBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.event.UserInfoEvent;
import com.funtonow.jqdk.fkcs.ui.DkSuccessActivity;
import com.funtonow.jqdk.fkcs.ui.FkMainActivity;
import com.funtonow.jqdk.service.CountDownBroadcastReceiver;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.StringUtil;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.tencent.captchasdk.TCaptchaPopupActivity;
import com.tencent.qcloud.logutils.LogActivity;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.GET_YZM;
import static com.funtonow.jqdk.base.Constants.INTO_LOGIN;
import static com.funtonow.jqdk.base.UrlUtils.BIND_CLIENTID;
import static com.funtonow.jqdk.base.UrlUtils.ED_JS;
import static com.funtonow.jqdk.base.UrlUtils.GET_SMS;
import static com.funtonow.jqdk.base.UrlUtils.SIGN_BY_SMS;

/**
 * @author Jiajien
 * @date 2019/6/18
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText edPhone;
    private EditText edSms;
    private TextView tvSendCode;
    private Button btnRegister;
    private TextView tvUserAgreement;
    private CheckBox checkBox;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;

    private CountDownTimer timer;
    private CountDownBroadcastReceiver countDownBroadcastReceiver;
    private Intent intent;


    @Override
    public int getLayoutRes() {
        return R.layout.activity_login;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar(getResources().getString(R.string.login));
        initView();
        if (AppUtils.getAppName(this).equals(getResources().getString(R.string.sqj_app_name))) {
            ivLogo.setImageResource(R.mipmap.ic_sqj_launcher);
        } else if (AppUtils.getAppName(this).equals(getResources().getString(R.string.yqs_app_name))) {
            ivLogo.setImageResource(R.mipmap.ic_launcher);
        } else {
            ivLogo.setImageResource(R.mipmap.ic_ssq_launcher);
        }
        countDownBroadcastReceiver = new CountDownBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //这里定义接受器监听广播的类型，这里添加相应的广播
        intentFilter.addAction("countdown.receiver");
        //实例化接收器
        //注册事件，将监听类型赋给对应的广播接收器----所以这叫动态注册
        registerReceiver(countDownBroadcastReceiver, intentFilter);
        MobclickAgent.onEvent(SqjAppliaction.getContext(), "login");
        mIbReturn.setVisibility(View.INVISIBLE);
        StatisticsUtils.eventLog(INTO_LOGIN, null);
    }

    private void initView() {
        edPhone = findViewById(R.id.et_phone);
        edSms = findViewById(R.id.et_sms);
        tvSendCode = findViewById(R.id.tv_send_code);
        btnRegister = findViewById(R.id.btn_register);
        tvUserAgreement = findViewById(R.id.tv_user_agreement);
        checkBox = findViewById(R.id.checkbox);
        tvSendCode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        tvUserAgreement.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    btnRegister.setClickable(true);
                    btnRegister.setBackgroundResource(R.drawable.btn_blue_layout);
                } else {
                    btnRegister.setClickable(false);
                    btnRegister.setBackgroundResource(R.drawable.btn_gray_layout);
                }
            }
        });
        edPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 11) {
                    tvSendCode.setClickable(true);
                    tvSendCode.setTextColor(getResources().getColor(R.color.color_333333));
                } else {
                    tvSendCode.setClickable(false);
                    tvSendCode.setTextColor(getResources().getColor(R.color.color_c7c7cc));
                }


                if (s.length() > 0) {
                    setDrawableLeft(R.mipmap.icon_phone, edPhone);
                } else {
                    setDrawableLeft(R.mipmap.icon_phone_normal, edPhone);
                }
            }
        });
        edSms.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    setDrawableLeft(R.mipmap.icon_yzm, edSms);
                } else {
                    setDrawableLeft(R.mipmap.icon_yzm_normal, edSms);
                }
            }
        });
        setAgreement();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send_code:
                tvSendCode.setClickable(false);
                if (StringUtil.isEmpty(edPhone.getText().toString()) && edPhone.getText().toString().length() >= 11) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                } else {
                    StatisticsUtils.eventLog(GET_YZM, null);
                    if (SqjAppliaction.loanInfoBean != null && SqjAppliaction.loanInfoBean.getInfo() != null) {
                        if (!SqjAppliaction.loanInfoBean.getInfo().getAdbannerid().equals("1")) {
                            getSms(edPhone.getText().toString(), "", "");
                        }
                    } else {
                        intent = new Intent(this, TCaptchaPopupActivity.class);
                        intent.putExtra("appid", Constants.SMS_APP_ID);
                        startActivityForResult(intent, 1);
                    }
                }
                break;
            case R.id.btn_register:
                if (StringUtil.isEmpty(edPhone.getText().toString()) && edPhone.getText().toString().length() >= 11) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                } else if (StringUtil.isEmpty(edSms.getText().toString())) {
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                } else {
                    signbysms(edPhone.getText().toString(), edSms.getText().toString());
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && data != null) {
            switch (resultCode) {
                case Activity.RESULT_OK: {
                    try {
                        JSONObject jsonObject = JSON.parseObject(data.getStringExtra("retJson"));
                        int ret = jsonObject.getInteger("ret");
                        if (ret == 0) {
                            //验证成功回调，此时ret=0，
                            //jsonObject.getInt("ticket")为验证码票据
                            //jsonObject.getString("appid")为appid
                            //jsonObject.getString("randstr")为随机串
                            getSms(edPhone.getText().toString(), String.valueOf(jsonObject.getString("ticket")), jsonObject.getString("randstr"));
                        } else if (ret == -1001) {
                            //验证码收个TCaptcha.js加载错误，业务可以根据需要重试
                            //jsonObject.getString("info")为错误信息
                        } else {
                            //验证失败回调，一般为用户关闭验证码弹框
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case Activity.RESULT_CANCELED: {
                    //用户按了返回键，关闭验证码未验证成功
                    break;
                }
                default:
                    break;
            }
        }
    }


    public void getSms(String phone, String ticket, String reandstr) {
        Map<String, String> params = new HashMap<>();
        params.put("p", phone);
        if (!StringUtil.isEmpty(ticket)) {
            params.put("t", ticket);
            params.put("r", reandstr);
        } else {
            params.put("x", "tk");
        }
        params.put("appid", Constants.OWN_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(GET_SMS, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {

                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") > 0) {
                    countDownTime(Integer.valueOf(jsonObject.getString("data")));
                } else {
                    Toast.makeText(LoginActivity.this, jsonObject.getString("errmsg"), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void countDownTime(int time) {
        /** 倒计时60秒，一次1秒 */
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                tvSendCode.setTextColor(getResources().getColor(R.color.color_3763fe));
                tvSendCode.setText(String.format(getString(R.string.countdown), millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                tvSendCode.setClickable(true);
                tvSendCode.setTextColor(getResources().getColor(R.color.color_333333));
                tvSendCode.setText("获取验证码");
            }
        }.start();
    }


    public void signbysms(String phone, String num) {
        Map<String, String> params = new HashMap<>();
        params.put("p", phone);
        params.put("appid", Constants.OWN_APP_ID);
        params.put("num", num);
        params.put("shebei", String.format("Android %s%s%s", Build.VERSION.RELEASE, PhoneUtils.getDeviceBrand(), PhoneUtils.getSystemModel()));
        params.put("channel", AppUtils.getAppMetaData(this, "UMENG_CHANNEL"));
        params.put("system", String.format("Android %s", Build.VERSION.RELEASE));
        params.put("viewuuid", SPUtil.getUUID());
        HttpUtil.getInstance().postDataAsynToNet(SIGN_BY_SMS, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(jsonString);
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum != 0) {
                    ToastUtils.show(jsonObject.getString("errmsg"));
                } else {
                    SPUtil.put("userInfo", baseBean.user);
                    bindClientId(jsonObject.getString("openid"));
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


    public void bindClientId(String openId) {
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.OWN_APP_ID);
        if (!StringUtil.isEmpty(openId)) {
            param.put("openid", openId);
        }
        param.put("cid", (String) SPUtil.get("clientId", ""));
        param.put("did", SPUtil.getUUID());
        HttpUtil.getInstance().postDataAsynToNet(BIND_CLIENTID, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                EventBus.getDefault().post(new UserInfoEvent());
                if (!AppUtils.getAppName(LoginActivity.this).equals(getString(R.string.ssq_app_name))) {
                    if (TimeUtils.isShowDialog()) {
                        Intent intent = new Intent("countdown.receiver");
                        intent.putExtra("msg", "广播");
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                            intent.setComponent(new ComponentName(getPackageName(), "com.funtonow.jqdk.service.CountDownBroadcastReceiver"));
                        }
                        sendBroadcast(intent);
                    }
                }
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                if (AppUtils.getAppName(LoginActivity.this).equals(getResources().getString(R.string.ssq_app_name))) {
                    getMoneyNum();
                } else {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        unregisterReceiver(countDownBroadcastReceiver);
    }

    /**
     * 设置用户协议
     */
    public void setAgreement() {
        SpannableStringBuilder spannable;
        String content;


        content = "登录即同意《用户服务协议》《隐私协议》";
        spannable = new SpannableStringBuilder(content);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(LoginActivity.this,
                        Constants.XYS_HTML, getResources().getString(R.string.xys), "");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 5, 14, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(LoginActivity.this,
                        Constants.YSS_HTML, getResources().getString(R.string.yss), "");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 14, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan span1 = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        ForegroundColorSpan span3 = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        spannable.setSpan(span1, 5, 14, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(span3, 14, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvUserAgreement.setHighlightColor(Color.TRANSPARENT);//去掉点击后的背景颜色为透明
        tvUserAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvUserAgreement.setText(spannable);
    }

    /**
     * 设置图片
     *
     * @param id
     * @param editText
     */
    private void setDrawableLeft(int id, EditText editText) {
        Drawable drawable = getResources().getDrawable(id, null);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        editText.setCompoundDrawables(drawable, null, null, null);

    }

    /**
     * 得到可贷款金额
     */
    private void getMoneyNum() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(ED_JS, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " *********  ");
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum == -2) {
                    startActivity(new Intent(LoginActivity.this, FkMainActivity.class));
                } else if (baseBean.errnum == 0) {
                    DkNumBean dkNumBean = JSON.parseObject(baseBean.data, DkNumBean.class);
                    switch (dkNumBean.getState()) {
                        case 1:
                        case 2:
                            Intent intent = new Intent(LoginActivity.this, DkSuccessActivity.class);
                            intent.putExtra("dkInfo", baseBean.data);
                            startActivity(intent);
                            break;
                        default:
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            break;
                    }
                }
                finish();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
